﻿#include "buss_addmenu.h"
#include "ui_buss_addmenu.h"
#include "buss_menu.h"
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QMessageBox>
#include <QFileDialog>
#include <QPixmap>
#include <QSqlError>
#include <QScreen>
#include <QGuiApplication>
Buss_addmenu::Buss_addmenu(int bus_id, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Buss_addmenu),
    bus_id(bus_id),
    m_currentStatus(3)//默认菜品上架
{
    ui->setupUi(this);
    setWindowTitle("添加菜品");
    
    // 获取屏幕尺寸并设置窗口大小为适合的比例
    QScreen *screen = QGuiApplication::primaryScreen();
    QRect screenGeometry = screen->geometry();
    int width = screenGeometry.width() * 0.5;  // 使用较小的尺寸，因为这是添加菜单窗口
    int height = screenGeometry.height() * 0.6;

    // 设置窗口大小并保持居中
    resize(width, height);
    move(screenGeometry.center() - rect().center());
    
    // 初始化数据库连接
    setupDatabase();
    
    // 初始化状态下拉框 - 只添加"上架"和"下架"选项
    ui->comboBox->clear();
    // 从数据库获取状态选项
     QSqlQuery query;
     query.exec("SELECT cs_id, status FROM commodity_status where cs_id=1 or cs_id=3");
     while (query.next()) {
       int id = query.value(0).toInt();
        QString status = query.value(1).toString();
        ui->comboBox->addItem(status, id); // 将ID与文本关联
        }

    // 设置价格范围
    ui->doubleSpinBox->setRange(0, 999);
    ui->doubleSpinBox->setSingleStep(0.5);

    // 设置图片标签属性
   ui->label_picture->setAlignment(Qt::AlignCenter);
   ui->label_picture->setText("<a href='select'>点击添加图片</a>"); // 设置为可点击链接
   ui->label_picture->setOpenExternalLinks(false); // 禁止打开外部链接
   ui->label_picture->setStyleSheet(
            "QLabel {"
            "border: 2px dashed #aaa;"
            "border-radius: 5px;"
            "background-color: #f9f9f9;"
            "padding: 10px;"
            "}"
        );
     // 连接信号槽
     connect(ui->label_picture, &QLabel::linkActivated,
     this, &Buss_addmenu::on_label_picture_linkActivated);

    // 自动填充商家名称
    setBusiness_id(bus_id);
}
Buss_addmenu::~Buss_addmenu()
{
    delete ui;
}

void Buss_addmenu::setupDatabase()
{
    db = QSqlDatabase::database();
    if (!db.isOpen()) {
        if (!db.open()) {
            QMessageBox::critical(this, "错误", "无法连接数据库: " + db.lastError().text());
            qDebug() << "数据库连接失败:" << db.lastError().text();
        }
    }
}

void Buss_addmenu::setBusiness_id(int bus_id)
{
    this->business_id = bus_id;
    // 根据商家ID查询并设置商家名称
    QSqlQuery query;
    query.prepare("SELECT business_name FROM business WHERE business_id = :business_id");
    query.bindValue(":business_id", bus_id);
    
    if (query.exec() && query.next()) {
        QString businessName = query.value(0).toString();
        ui->lineEdit_bussner->setText(businessName);
        ui->lineEdit_bussner->setReadOnly(true); // 设置为只读，防止用户修改
        qDebug() << "设置商家名称:" << businessName;
    } else {
        qDebug() << "无法获取商家名称:" << query.lastError().text();
    }
}

//图片点击
void Buss_addmenu::on_label_picture_linkActivated(const QString &link)
{
    Q_UNUSED(link); // 不使用传入的链接参数

    QString fileName = QFileDialog::getOpenFileName(
        this,
        "选择菜品图片",
        "",
        "图片文件 (*.png *.jpg *.jpeg *.bmp)"
    );

    if (!fileName.isEmpty()) {
        QPixmap pixmap(fileName);
        if (!pixmap.isNull()) {
            // 缩放图片以适应标签大小
            pixmap = pixmap.scaled(
                ui->label_picture->size(),
                Qt::KeepAspectRatio,
                Qt::SmoothTransformation
            );
            ui->label_picture->setPixmap(pixmap);
            m_imagePath = fileName; // 保存图片路径
        } else {
            QMessageBox::warning(this, "警告", "无法加载图片文件!");
        }
    }
}
//添加完成，并跳回到菜单
void Buss_addmenu::on_pushButton_add_clicked()
{
    //QString businessName = ui->lineEdit_bussner->text();
    QString menuName = ui->lineEdit_menu->text();
    QString description = ui->lineEdit_drection->text();
    int statusId = ui->comboBox->currentData().toInt(); // 获取状态ID
    double price = ui->doubleSpinBox->value();

        if (menuName.isEmpty() || price <= 0) {
            QMessageBox::warning(this, "警告", "请填写完整的菜品信息!");
            return;
        }
        QSqlQuery query;

        query.prepare("INSERT INTO commodity (business_id, com_name, price, description, img, cs_id) "
                         "VALUES (:business_id, :com_name, :price, :description, :img, :cs_id)");

        query.bindValue(":business_id", business_id);
        query.bindValue(":com_name", menuName);
        query.bindValue(":price", price);
        query.bindValue(":description", description);
        query.bindValue(":img",m_imagePath); // 添加图片路径
        query.bindValue(":cs_id", statusId); // 添加销售状态ID

        if (query.exec()) {
            QMessageBox::information(this, "成功", "菜品添加成功!");
            emit menuAdded(); // 发送添加完成信号
            // 添加跳转回菜单界面的代码
             Buss_menu *menu = new Buss_menu(business_id);
             menu->show();
             this->hide();
        } else {
            QMessageBox::critical(this, "错误", "添加失败: " + query.lastError().text());
        }
}

//返回菜单界面
void Buss_addmenu::on_pushButton_return_clicked()
{
    Buss_menu *b =new Buss_menu(business_id);
    b->show();
    this->hide();
}
